namespace Digitalmes.Application.Mes;

/// <summary>
/// 工艺路线表服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "mes")]
public sealed class ProcRoutingService : IDynamicWebApiService
{
    private readonly SugarRepository<ProcRouting> _thisRepository;
    private readonly SugarRepository<MdLine> _lineRepo;

    public ProcRoutingService(SugarRepository<ProcRouting> thisRepository, SugarRepository<MdLine> lineRepo)
    {
        _thisRepository = thisRepository;
        _lineRepo = lineRepo;
    }

    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ProcRoutingDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ProcRoutingDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ProcRoutingDto> GetAsync(long id)
    {
        var model = await _thisRepository.GetByIdAsync(id);
        return model.Adapt<ProcRoutingDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> AddAsync(ProcRoutingDto model)
    {
        if (await _thisRepository.IsAnyAsync(s => s.RoutingCode == model.RoutingCode))
        {
            Oops.ThrowBah(ErrCode.E4002);
        }

        var line = await _lineRepo.GetFirstAsync(s => s.Id == model.LineId);
        var routing = model.Adapt<ProcRouting>();
        routing.LineCode = line.LineCode;

        return await _thisRepository.InsertAsync(routing);
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(ProcRoutingDto model)
    {
        if (await _thisRepository.IsAnyAsync(s => s.RoutingCode == model.RoutingCode && s.Id != model.Id))
        {
            Oops.ThrowBah(ErrCode.E4002);
        }

        var routing = model.Adapt<ProcRouting>();
        return await _thisRepository.UpdateAsync(routing, s => new { s.RoutingName, s.UpdateTime, s.UpdateUser });
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody] List<long> ids) =>
        await _thisRepository.DeleteAsync(m => ids.Contains(m.Id));
}
